<?php
namespace support;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class Paypal
{
    private $clientId;
    private $clientSecret;
    private $apiUrl;
    private $client;
    private $returnUrl;
    private $cancelUrl;

    public function __construct($clientId, $clientSecret, $isSandbox = true)
    {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
        $this->apiUrl = $isSandbox ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
        $this->client = new Client();
    }

    public function setReturnUrl($returnUrl)
    {
        $this->returnUrl = $returnUrl;
    }

    public function setCancelUrl($cancelUrl)
    {
        $this->cancelUrl = $cancelUrl;
    }

    private function getAccessToken()
    {
        try {
            $response = $this->client->post($this->apiUrl . '/v1/oauth2/token', [
                'auth' => [$this->clientId, $this->clientSecret],
                'form_params' => [
                    'grant_type' => 'client_credentials'
                ],
                'headers' => [
                    'Accept' => 'application/json',
                    'Accept-Language' => 'en_US'
                ]
            ]);
            $result = json_decode($response->getBody(), true);
            return $result['access_token'];
        } catch (RequestException $e) {
            $this->handleException($e);
            return null;
        }
    }

    public function createOrder($amount, $orderNo, $currency = 'USD')
    {
        $accessToken = $this->getAccessToken();
        if (!$accessToken) {
            return null;
        }
        try {
            $orderData = [
                'intent' => 'CAPTURE',
                'purchase_units' => [
                    [
                        'amount' => [
                            'currency_code' => $currency,
                            'value' => $amount
                        ],
                        'custom_id' => $orderNo
                    ]
                ]
            ];

            if ($this->returnUrl && $this->cancelUrl) {
                $orderData['application_context'] = [
                    'return_url' => $this->returnUrl,
                    'cancel_url' => $this->cancelUrl
                ];
            }

            $response = $this->client->post($this->apiUrl . '/v2/checkout/orders', [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $accessToken
                ],
                'json' => $orderData
            ]);
            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $this->handleException($e);
            return null;
        }
    }

    public function capturePayment($orderId)
    {
        $accessToken = $this->getAccessToken();
        if (!$accessToken) {
            return null;
        }
        try {
            $response = $this->client->post($this->apiUrl . '/v2/checkout/orders/' . $orderId . '/capture', [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $accessToken
                ]
            ]);
            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $this->handleException($e);
            return null;
        }
    }

    public function verifyWebhook($webhookId, $headers, $body)
    {
        $accessToken = $this->getAccessToken();
        if (!$accessToken) {
            return false;
        }
        try {
            $response = $this->client->post($this->apiUrl . '/v1/notifications/verify-webhook-signature', [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $accessToken
                ],
                'json' => [
                    'transmission_id' => $headers['paypal-transmission-id'],
                    'transmission_time' => $headers['paypal-transmission-time'],
                    'cert_url' => $headers['paypal-cert-url'],
                    'auth_algo' => $headers['paypal-auth-algo'],
                    'transmission_sig' => $headers['paypal-transmission-sig'],
                    'webhook_id' => $webhookId,
                    'webhook_event' => json_decode($body, true)
                ]
            ]);
            $result = json_decode($response->getBody(), true);
            return $result['verification_status'] === 'SUCCESS';
        } catch (RequestException $e) {
            $this->handleException($e);
            return false;
        }
    }

    private function handleException(RequestException $e)
    {
        if ($e->hasResponse()) {
            $response = json_decode($e->getResponse()->getBody(), true);
            error_log('PayPal API Error: ' . json_encode($response));
        } else {
            error_log('PayPal API Request Error: ' . $e->getMessage());
        }
    }
}